import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '../views/Login/Login.vue'
import Reg from '../views/Reg/Reg.vue'
import Main from '../views/Main/Main.vue'
import store from '../store'
import Home from '../views/menus/Home/Home.vue'
import UserInfo from '../views/menus/User/UserInfo.vue'
import UserAvatar from '../views/menus/User/UserAvatar.vue'
import UserPwd from '../views/menus/User/UserPwd.vue'
import ArtCate from '../views/menus/article/ArtCate.vue'
import ArtLi from '../views/menus/article/ArtList.vue'
Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  { path: '/login', name: 'Login', component: Login },
  { path: '/reg', name: 'Reg', component: Reg },
  {
    path: '/',
    name: 'Main',
    component: Main,
    // 3. 开启路由重定向
    redirect: '/home',
    // 2. home 作为 子路由规则
    children: [
      { path: 'home', name: 'Home', component: Home },
      // 用户信息的子路由规则
      { path: 'user-info', name: 'UserInfo', component: UserInfo },
      { path: 'user-avatar', name: 'UserAvatar', component: UserAvatar },
      { path: 'user-pwd', name: 'UserPwd', component: UserPwd },
      { path: 'art-cate', name: 'ArtCate', component: ArtCate },
      { path: 'art-list', name: 'ArtLi', component: ArtLi }

    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path === '/' && !store.state.token) {
    // this.$message.error('请先登录哦!')
    Vue.prototype.$message.error('请先登录哦!')
    return next('/login')
  }
  next()
})

export default router
